import com.android.build.api.transform.*
import com.android.build.gradle.internal.pipeline.TransformManager
import com.android.utils.FileUtils
import java.io.File
import java.util.jar.JarFile

/**
 *
 *
 * @author Ysj
 * Create time: 2021/9/15
 */
class BuildSrcTransform : Transform() {

    override fun getName(): String = "buildSrcTest"

    override fun getInputTypes(): MutableSet<QualifiedContent.ContentType> =
        TransformManager.CONTENT_CLASS

    override fun getScopes(): MutableSet<in QualifiedContent.Scope> =
        TransformManager.SCOPE_FULL_PROJECT

    override fun isIncremental(): Boolean = false

    override fun transform(transformInvocation: TransformInvocation) {
        super.transform(transformInvocation)
        // 当前 gradle 运行环境上下文。可以拿到日志等级，当前 project 名称路径等信息
        val context = transformInvocation.context
        // 是否支持增量
        val incremental = transformInvocation.isIncremental
        // 配合增量的输入
        val secondaryInputs = transformInvocation.secondaryInputs
        // 引用输入。该输入处理后不需要输出
        val referencedInputs = transformInvocation.referencedInputs

        // 普通输入。通常用该输入处理，该输入处理完后需要输出到指定位置
        val inputs = transformInvocation.inputs
        // 用于提供输出的位置。注意：该输出会变成下个 Transform 的输入
        val outputProvider = transformInvocation.outputProvider
        // 演示 Transform
        transform(inputs, outputProvider)
    }

    private fun transform(inputs: MutableCollection<TransformInput>, output: TransformOutputProvider) {
        output.deleteAll()
        inputs.forEach {
            // 目录输入源。也就是源码
            val directoryInputs = it.directoryInputs
            // jar 包输入源
            val jarInputs = it.jarInputs
            // 处理 directoryInputs
            directoryInputs.forEach { input ->
                val src = input.file
                val dest = output.getContentLocation(
                    input.name,
                    input.contentTypes,
                    input.scopes,
                    Format.DIRECTORY
                )
                FileUtils.copyDirectory(src, dest)
                dest.walk().forEach { file ->
                    if (file.isFile) println("dir input --> $file")
                }
            }
            // 处理 jar
            jarInputs.forEach { input ->
                val src = input.file
                val dest = output.getContentLocation(
                    input.name,
                    input.contentTypes,
                    input.scopes,
                    Format.JAR
                )
                FileUtils.copyFile(src, dest)
                JarFile(src).use { jf ->
                    // 遍历 jar 文件中的内容
                    val entries = jf.entries()
                    while (entries.hasMoreElements()) {
                        val elem = entries.nextElement()
                        println("jar file: ${src.name} elem:${elem.name}")
                    }
                }
            }
        }
    }


}